package com.project.config;

import com.project.entity.po.Admin;
import com.project.entity.po.User;
import com.project.result.ResponseResult;
import com.project.service.AdminService;
import com.project.service.RolePermissionService;
import com.project.service.UserService;
import com.project.entity.vo.RoleVo;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @ProjectName:
 * @Package:
 * @ClassName:
 * @Author: ZhaoLongShi
 * @CreateDate:
 */
@SuppressWarnings("all")
public class AdminRealm extends AuthorizingRealm {
    @Resource
     UserService userService;
    @Resource
    AdminService adminService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        ResponseResult result = adminService.selectAdminByName(username);
        Admin admin = (Admin) result.getData();
        if (admin == null) {
            throw new UnknownAccountException();
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo =
                new SimpleAuthenticationInfo(admin, admin.getPassword(), null, username);
        return simpleAuthenticationInfo;
    }

    @Resource
    RolePermissionService rolePermissionService;

    /**
     * 权限操作
     * 基于权限访问
     * 基于角色访问
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //1. 获取前端发送的用户信息
        User user = (User) principals.getPrimaryPrincipal();
        //2. 获取用户的角色信息
        ResponseResult responseResult = rolePermissionService.selectRolesById(user.getUserId());
        List<RoleVo> roleVos = (List<RoleVo>) responseResult.getData();
        //3. 转化数据，存储进 simpleAuthenticationInfo 里面
        Set<String> roles = new HashSet<>();
        Set<String> permissions = new HashSet<>();
        //遍历角色
        roleVos.forEach(roleVo -> {
            //角色名称添加到集合中
            roles.add(roleVo.getRoleName());
            //遍历权限
            roleVo.getPermissions().forEach(permissionVo -> {
                //权限名称添加到集合中
                permissions.add(permissionVo.getPermissionName());
            });
        });
        simpleAuthorizationInfo.setRoles(roles);
        simpleAuthorizationInfo.setStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }
}
